package com.mdnote.structure.array_queue;

import java.util.Scanner;

/**
 * @author Rhythm-2019
 * @date 2020/8/9
 * @description 环形队列
 */
public class CircleArrayQueue {

    private int[] data;

    // 队尾，约定预留一个位置用于，如果头 = 胃表示队列为空，如果相差 1 个位置说明队列已经满了
    private int rear;

    // 队头
    private int front;

    // 数组最大个数
    private int maxSize;

    private CircleArrayQueue(int size) {
        this.data = new int[size];
        // 从0起，从-1开始优点难打印
        this.front = 0;
        this.rear = 0;
        this.maxSize = size;
    }

    public boolean isEmpty() {
        return front == rear;
    }

    public boolean isFull() {
        // 预留一个位置
//        return size() == maxSize - 1;
        return (rear + 1) % maxSize == front;
    }
    public int size() {
        return (rear - front + maxSize) % maxSize;
    }
    public void add(int value) {
        if (isFull()) {
            throw new RuntimeException("queue is full");
        }
        data[rear] = value;
        rear = (rear + 1) % maxSize;
    }
    public int get() {
        if (isEmpty()) {
            throw new RuntimeException("queue is empty");
        }
        int val = data[front] ;
        front = (front + 1) % maxSize;
        return val;
    }
    public int peak() {
        return data[front];
    };

    private void show() {
        if (isEmpty()) {
            System.out.println("queue is empty");
            return;
        }
        for (int i = front; i < size() + front; i++) {
            System.out.printf("arr[%d]=%d\n", i % maxSize, this.data[i % maxSize]);
        }
    }
    public static void main(String[] args) {

        CircleArrayQueue arrayQueue = new CircleArrayQueue(3);

        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("p[peak]");
            System.out.println("a[add]");
            System.out.println("r[remove]");
            System.out.println("s[show]");
            System.out.println("e[exit]");

            char flag = scanner.next().charAt(0);
            switch (flag) {
                case 'a' :
                    try {
                        arrayQueue.add(scanner.nextInt());
                    } catch (Exception e) {
                        System.out.println(e.getMessage());
                    }
                    break;
                case 'p':
                    System.out.println("输出：" + arrayQueue.peak());
                    break;
                case 'r':
                    arrayQueue.get();
                    break;
                case 's':
                    arrayQueue.show();
                    break;
                case 'e':
                    System.exit(0);


            }

        }
    }



}
